<template style="height: 100%">
    <div class="eva-container">
        <div class="eva-card">
            <div class="eva-layout">
                <aside class="eva-sidebar">
                    <div class="sidebar-header">
                        <div class="eva-avatar">
                            <el-avatar :size="48" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"></el-avatar>
                        </div>
                        <div class="sidebar-title">Eva 会话</div>
                    </div>
                    <div class="sidebar-actions">
                        <el-button type="primary" size="mini" icon="el-icon-plus" @click="handleAddSession" :loading="sessionsLoading" class="full-width">新建会话</el-button>
                        <el-button size="mini" icon="el-icon-question" @click="showHelp" class="full-width">帮助</el-button>
                    </div>
                    <div class="session-list" :class="{ loading: sessionsLoading }">
                        <div
                            v-for="(s, idx) in sessions"
                            :key="s.sessionId || s.id || idx"
                            :class="['session-item', (s.sessionId || s.id) === currentSessionId ? 'active' : '']"
                        >
                            <!-- 可点击的内容区域 -->
                            <div class="session-content" @click="selectSession(s)">
                                <div class="session-name">{{ s.title || ('会话 ' + (idx + 1)) }}</div>
                            </div>

                            <!-- 独立的删除按钮区域 -->
                            <div class="session-actions">
                                <el-button
                                    size="mini"
                                    icon="el-icon-delete"
                                    @click="confirmDeleteSession(s)"
                                    type="danger"
                                    circle
                                ></el-button>
                            </div>
                        </div>
                        <div v-if="!sessionsLoading && sessions.length === 0" class="session-empty">暂无会话，点击上方"新建会话"开始</div>
                    </div>
                </aside>
                <main class="eva-main">
                    <div class="eva-header">
                        <div class="eva-avatar">
                            <el-avatar :size="60" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"></el-avatar>
                        </div>
                        <div class="eva-info">
                            <h2 class="eva-title">学院AI小助手Eva</h2>
                            <div class="eva-status">
                                <span class="status-dot"></span>
                                <span class="status-text">在线</span>
                            </div>
                        </div>
                        <div class="eva-actions">
                            <el-button type="text" icon="el-icon-delete-solid" @click="clearChat" title="清空对话"></el-button>
                            <el-button type="text" icon="el-icon-question" @click="showHelp" title="帮助"></el-button>
                        </div>
                    </div>

                    <div class="eva-divider"></div>

                    <div class="chat-body">
                        <div class="eva-messages" ref="messageListContainer" @scroll.passive="onScrollMessages">
                            <div v-if="messageList.length === 0" class="empty-chat">
                                <div class="empty-icon">
                                    <i class="el-icon-chat-dot-round"></i>
                                </div>
                                <p>欢迎使用学院AI小助手Eva，有什么可以帮您的吗？</p>
                                <div class="quick-prompts">
                                    <div class="prompt-title">快速提问：</div>
                                    <div class="prompt-tags">
                                        <el-tag
                                            v-for="(prompt, index) in quickPrompts"
                                            :key="index"
                                            size="small"
                                            @click="usePrompt(prompt)"
                                            class="prompt-tag">
                                            {{ prompt }}
                                        </el-tag>
                                    </div>
                                </div>
                            </div>

                            <ul v-else class="message-list">
                                <li v-for="(message, index) in messageList" :key="index" class="message-item">
                                    <div :class="message.from === 'assistant' ? 'eva-message' : 'user-message'">
                                        <div class="message-line">
                                            <div class="avatar-container" v-if="message.from === 'assistant' || message.from === 'eva'">
                                                <el-avatar :size="36" src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"></el-avatar>
                                            </div>
                                            <div class="message-content">
                                                <div class="message-text">{{ message.text }}</div>
                                                <div class="message-time">{{ formatMessageTime(message) }}</div>
                                            </div>
                                            <div class="avatar-container" v-if="message.from === 'user'">
                                                <el-avatar :size="36" :src="$store.state.me ? $store.state.me.userPicture : ''"></el-avatar>
                                            </div>
                                        </div>
                                    </div>
                                </li>
                            </ul>
                        </div>

                        <div class="quick-prompts-fixed" v-if="messageList.length > 0">
                            <div class="prompt-title">快速提问：</div>
                            <div class="prompt-tags">
                                <el-tag
                                    v-for="(prompt, index) in quickPrompts"
                                    :key="index"
                                    size="small"
                                    @click="usePrompt(prompt)"
                                    class="prompt-tag">
                                    {{ prompt }}
                                </el-tag>
                            </div>
                        </div>

                        <div class="eva-input-area">
                            <div v-if="!loading" class="input-container">
                                <div class="input-toolbar">
                                    <el-button type="text" icon="el-icon-picture" @click="showEmojiPicker = !showEmojiPicker" title="表情"></el-button>
                                    <el-button type="text" icon="el-icon-upload" @click="uploadImage" title="上传图片"></el-button>
                                    <input type="file" ref="imageInput" style="display: none" accept="image/*" @change="handleImageUpload">
                                </div>

                                <el-input
                                    clearable
                                    type="textarea"
                                    :rows="3"
                                    placeholder="请输入您的问题..."
                                    v-model="InputMessage"
                                    @keyup.enter.native="send"
                                    resize="none"
                                    class="message-input">
                                </el-input>

                                <div class="input-actions">
                                    <el-button type="primary" @click="send" :disabled="!InputMessage.trim()" class="send-button">
                                        <i class="el-icon-s-promotion"></i> 发送
                                    </el-button>
                                </div>

                                <div class="emoji-picker" v-if="showEmojiPicker">
                                    <div class="emoji-list">
                                        <span
                                            v-for="(emoji, index) in emojis"
                                            :key="index"
                                            class="emoji-item"
                                            @click="insertEmoji(emoji)">
                                            {{ emoji }}
                                        </span>
                                    </div>
                                </div>
                            </div>
                            <div v-else class="typing-indicator">
                                <div class="loader">
                                    <div class="circle">
                                        <div class="dot"></div>
                                        <div class="outline"></div>
                                    </div>
                                </div>
                                <span class="typing-text">Eva正在思考中...</span>
                            </div>
                        </div>
                    </div>
                </main>
            </div>
        </div>

        <div v-if="loading" class="loading-overlay">
            <loading/>
        </div>

        <!-- 帮助对话框 -->
        <el-dialog
            title="AI小助手使用帮助"
            :visible.sync="helpDialogVisible"
            width="50%"
            custom-class="help-dialog">
            <div class="help-content">
                <h3>如何使用Eva</h3>
                <p>Eva是学院的AI小助手，可以帮助您解答关于学院的各种问题，包括：</p>
                <ul>
                    <li>学院基本信息查询</li>
                    <li>课程安排咨询</li>
                    <li>活动信息获取</li>
                    <li>常见问题解答</li>
                </ul>
                <p>您可以直接输入问题，Eva会尽力为您提供准确的回答。</p>

                <h3>功能特点</h3>
                <div class="feature-grid">
                    <div class="feature-item">
                        <i class="el-icon-chat-dot-round"></i>
                        <span>智能对话</span>
                    </div>
                    <div class="feature-item">
                        <i class="el-icon-question"></i>
                        <span>问题解答</span>
                    </div>
                    <div class="feature-item">
                        <i class="el-icon-info"></i>
                        <span>信息查询</span>
                    </div>
                    <div class="feature-item">
                        <i class="el-icon-time"></i>
                        <span>24小时在线</span>
                    </div>
                </div>
            </div>
        </el-dialog>

        <!-- 确认删除对话框 -->
        <el-dialog
            title="确认删除"
            :visible.sync="deleteDialogVisible"
            width="30%"
            center>
            <span>确定要删除会话 "{{ deleteSessionTitle }}" 吗？删除后无法恢复。</span>
            <span slot="footer" class="dialog-footer">
                <el-button @click="deleteDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleDeleteSession" :loading="deleting">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import {
    cleanEvaChat,
    postPic,
    getEvaSessions,
    addEvaSession,
    getEvaHistory,
    deleteSession,
    deleteMessage
} from "@/api/api";
import Loading from "@/components/Loading.vue";

export default {
    components: {Loading},
    data() {
        return {
            loading: false,
            InputMessage: "",
            eventSource: null,
            debounceTimer: null,
            helpDialogVisible: false,
            showEmojiPicker: false,
            currentSessionId: 0,
            sessions: [],
            sessionsLoading: false,
            messageListLocal: [],
            pageNumber: 1,
            pageSize: 20,
            hasMore: true,
            isLoadingHistory: false,
            preserveScrollHeight: 0,
            emojis: ["😊", "😂", "🤔", "👍", "❤️", "🙏", "🎉", "🔥", "💡", "📚", "🎓", "🏫", "⏰", "📅", "📝", "🔍"],
            quickPrompts: [
                "学院有哪些专业？",
                "如何申请奖学金？",
                "校园活动有哪些？",
                "图书馆开放时间？",
                "如何联系辅导员？"
            ],
            // 删除相关状态
            deleteDialogVisible: false,
            deleting: false,
            deleteSessionId: null,
            deleteSessionTitle: ''
        };
    },
    computed: {
        messageList() {
            return this.messageListLocal;
        }
    },
    mounted() {
        this.scrollToBottom();
    },
    beforeDestroy() {
        if (this.eventSource) {
            this.eventSource.close();
        }
        window.removeEventListener('beforeunload', this.handleBeforeUnload);
        clearTimeout(this.debounceTimer);
    },
    created() {
        this.bootstrapSessions();
    },
    methods: {
        formatSessionTime(ts) {
            const d = new Date(ts);
            const mm = (d.getMonth() + 1).toString().padStart(2, '0');
            const dd = d.getDate().toString().padStart(2, '0');
            const hh = d.getHours().toString().padStart(2, '0');
            const mi = d.getMinutes().toString().padStart(2, '0');
            return `${mm}-${dd} ${hh}:${mi}`;
        },
        async bootstrapSessions() {
            this.sessionsLoading = true;
            try {
                const res = await getEvaSessions();
                const list = res.data.data.list;
                this.sessions = Array.isArray(list) ? list : [];
                if (this.sessions.length > 0) {
                    this.selectSession(this.sessions[0]);
                } else {
                    // 如果没有会话则创建一个
                    await this.handleAddSession();
                }
            } catch (e) {
                this.$message.error('获取会话列表失败');
            } finally {
                this.sessionsLoading = false;
            }
        },
        async handleAddSession() {
            try {
                const res = await addEvaSession();
                console.log("addEvaSession", res.data.message)
                if (res.data.message==="成功") {
                    // 重新获取一次完整会话列表，确保与后端状态一致
                    this.sessionsLoading = true;
                    try {
                        const res = await getEvaSessions();
                        const list = res.data.data.list;
                        this.sessions = Array.isArray(list) ? list : [];
                    } catch (e) {
                        this.$message.error('获取会话列表失败');
                    } finally {
                        this.sessionsLoading = false;
                    }
                } else {
                    this.$message.warning('创建会话成功，但未返回会话ID');
                }
            } catch (e) {
                this.$message.error('创建会话失败');
            }
        },
        async refreshSessionsAndSelect(targetSessionId) {
            this.sessionsLoading = true;
            try {
                const res = await getEvaSessions();
                const list = res.data.data.list;
                this.sessions = Array.isArray(list) ? list : [];
                const found = this.sessions.find(x => (x.sessionId || x.id) === targetSessionId);
                if (found) {
                    this.selectSession(found);
                } else if (this.sessions.length > 0) {
                    this.selectSession(this.sessions[0]);
                }
            } catch (e) {
                this.$message.error('刷新会话列表失败');
            } finally {
                this.sessionsLoading = false;
            }
        },
        selectSession(session) {
            const sid = session && (session.sessionId || session.id);
            if (!sid) return;
            if (this.currentSessionId === sid) return;
            this.currentSessionId = sid;
            // 重置分页与消息
            this.pageNumber = 1;
            this.hasMore = true;
            this.messageListLocal = [];
            this.loadHistory(true);
        },
        async loadHistory(isInitial = false) {
            if (!this.currentSessionId) return;
            if (this.isLoadingHistory) return;
            if (!this.hasMore && !isInitial) return;
            this.isLoadingHistory = true;
            try {
                const res = await getEvaHistory(this.currentSessionId, { PageNumber: this.pageNumber, PageSize: this.pageSize });
                const list = res.data.list;
                const mapped = (list || []).map(this.mapHistoryMessage).sort((a,b) => (a.id||0) - (b.id||0));
                if (this.pageNumber === 1) {
                    this.messageListLocal = mapped;
                    this.$nextTick(this.scrollToBottom);
                } else {
                    const container = this.$refs.messageListContainer;
                    if (container) this.preserveScrollHeight = container.scrollHeight;
                    this.messageListLocal = [...mapped, ...this.messageListLocal];
                    this.$nextTick(() => {
                        const c = this.$refs.messageListContainer;
                        if (c) c.scrollTop = c.scrollHeight - this.preserveScrollHeight;
                    });
                }
                if (!list || list.length < this.pageSize) this.hasMore = false;
            } catch (e) {
                this.$message.error('获取历史消息失败');
            } finally {
                this.isLoadingHistory = false;
            }
        },
        onScrollMessages(e) {
            const el = e && e.target ? e.target : this.$refs.messageListContainer;
            if (!el) return;
            if (el.scrollTop === 0 && this.hasMore && !this.isLoadingHistory) {
                this.pageNumber += 1;
                this.loadHistory(false);
            }
        },
        mapHistoryMessage(m) {
            const id = m.id || m.time || Date.now();
            const role = m.from || m.role || '';
            // 处理不同类型的消息来源，确保兼容性
            const from = (role === 'assistant' || role === 'ASSISTANT' || role === 'system' || role === 'eva' || role === 'EVA') ? 'assistant' : 'user';
            // 处理不同格式的消息内容
            const text = m.text || m.content || m.message || m.messageText || '';
            return { id, from, text };
        },
        formatMessageTime(message) {
            if (!message.id) return '';

            const date = new Date(message.id);
            const hours = date.getHours().toString().padStart(2, '0');
            const minutes = date.getMinutes().toString().padStart(2, '0');

            return `${hours}:${minutes}`;
        },
        showHelp() {
            this.helpDialogVisible = true;
        },
        clearChat() {
            this.$confirm('确定要清空所有对话记录吗?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(async () => {
                const res = await deleteMessage(this.currentSessionId);
                if (res.data.message === "成功") {
                    this.$message({
                        type: 'success',
                        message: '对话已清空!'
                    });
                    this.messageListLocal = [];
                }
                else {
                    this.$message.error('清空对话记录失败');
                }
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消清空'
                });
            });
        },
        // 确认删除会话（弹出确认框）
        confirmDeleteSession(session) {
            this.deleteSessionId = session.sessionId || session.id;
            this.deleteSessionTitle = session.title || `会话 ${this.sessions.indexOf(session) + 1}`;
            this.deleteDialogVisible = true;
        },
        // 执行删除会话
        async handleDeleteSession() {
            if (!this.deleteSessionId) return;

            this.deleting = true;
            try {
                const response = await deleteSession(this.deleteSessionId);
                console.log( response);
                if (response && response.data.message === "成功") {
                    this.$message.success('删除成功');

                    // 从会话列表中移除
                    this.sessions = this.sessions.filter(s =>
                        (s.sessionId || s.id) !== this.deleteSessionId
                    );

                    // 如果删除的是当前会话，清空当前会话
                    if (this.currentSessionId === this.deleteSessionId) {
                        this.currentSessionId = null;
                        // 清空消息等
                        this.clearCurrentSession();
                    }

                    this.deleteDialogVisible = false;
                } else {
                    this.$message.error('删除失败!');
                }
            } catch (error) {
                console.error('删除失败:', error);
                this.$message.error('删除失败123');
            } finally {
                this.deleting = false;
                this.deleteSessionId = null;
                this.deleteSessionTitle = '';
            }
        },
        // 清空当前会话
        clearCurrentSession() {
            // 清空当前会话相关的数据
            this.messageListLocal = [];
            // 其他清理逻辑...
        },
        async handleBeforeUnload() {
            try {
                const response = await cleanEvaChat();
                console.log(response.code === 200 ? "清空成功" : "清空失败");
            } catch (error) {
                console.error("清空失败:", error);
            }
        },
        async init() {
            this.loading = true;
            try {
                await this.streamEvaResponse("你好，你是谁");
            } catch (error) {
                console.error("请求失败:", error);
                this.$message.error("初始化失败");
            } finally {
                this.loading = false;
            }
        },
        async send() {
            // 验证输入和会话状态
            if (!this.InputMessage.trim()) return;
            if (!this.currentSessionId) {
                this.$message.warning('请先选择或新建会话');
                return;
            }

            // 设置加载状态并保存用户消息
            this.loading = true;
            const userMessage = this.InputMessage;
            this.InputMessage = "";

            // 添加用户消息到消息列表
            const userMessageId = Date.now() - 1;
            this.messageListLocal.push({
                id: userMessageId,
                text: userMessage,
                from: 'user'
            });
            this.scrollToBottom();

            try {
                // 调用流式响应方法获取AI回复
                await this.streamEvaResponse(userMessage);
            } catch (error) {
                console.error("请求失败:", error);
                this.$message.error("获取回复失败");
            } finally {
                this.loading = false;
                this.scrollToBottom();
            }
        },
        async streamEvaResponse(message) {
            // 创建一个新的消息ID并添加到消息列表
            const messageId = Date.now();
            this.messageListLocal.push({ id: messageId, text: '', from: 'assistant', isStreaming: true });

            // 从path.js和baseUrl.js中获取的配置
            const token = localStorage.getItem('Authorization');

            // 构建URL，确保sessionId参数正确传递
            // 注意：后端接口需要Integer类型的sessionId，确保转换正确
            const sessionIdParam = this.currentSessionId ? parseInt(this.currentSessionId) : 0;
            const url = `http://localhost:9000/dc/eva/chat?message=${encodeURIComponent(message)}&sessionId=${sessionIdParam}`;

            let fullMessage = '';
            // 用于跟踪是否已经处理过[complete]标记
            let isCompleted = false;
            // 用于调试，记录接收到的所有数据
            let allReceivedData = '';
            // 用于跟踪连接状态
            let connectionActive = true;
            // 重试次数
            let retryCount = 0;
            // 最大重试次数
            const maxRetries = 3;
            // 定义一个异步函数来处理SSE连接，包括重试逻辑
            const connectToSSE = async () => {
                try {
                    console.log(`尝试连接SSE，重试次数: ${retryCount}`);

                    // 使用fetch API发起SSE请求，添加超时处理
                    const controller = new AbortController();
                    const timeoutId = setTimeout(() => {
                        controller.abort();
                        console.error('SSE连接超时');
                    }, 30000); // 30秒超时

                    const response = await fetch(url, {
                        method: 'GET',
                        headers: {
                            'Authorization': token,
                            'Accept': 'text/event-stream'
                        },
                        signal: controller.signal
                    });

                    // 清除超时计时器
                    clearTimeout(timeoutId);

                    if (!response.ok) {
                        throw new Error(`HTTP error! status: ${response.status}`);
                    }

                    return response;
                } catch (error) {
                    console.error('SSE连接错误:', error);
                    if (retryCount < maxRetries && connectionActive) {
                        retryCount++;
                        console.log(`将在2秒后重试，剩余重试次数: ${maxRetries - retryCount}`);
                        await new Promise(resolve => setTimeout(resolve, 2000)); // 等待2秒后重试
                        return await connectToSSE(); // 递归重试
                    } else {
                        throw error; // 超过最大重试次数，抛出错误
                    }
                }
            };

            try {
                // 连接到SSE
                const response = await connectToSSE();

                // 使用ReadableStream API处理流数据
                const reader = response.body.getReader();
                const decoder = new TextDecoder('utf-8');
                let buffer = '';

                // 设置一个标志，表示是否已经收到了数据
                let hasReceivedData = false;

                // 设置一个心跳检测，确保连接活跃
                const heartbeatInterval = setInterval(() => {
                    if (!connectionActive) {
                        clearInterval(heartbeatInterval);
                        return;
                    }

                    if (!hasReceivedData && !isCompleted) {
                        console.log('SSE心跳检测：尚未收到数据...');
                    }
                }, 5000); // 每5秒检查一次

                try {
                    while (connectionActive && !isCompleted) {
                        const { done, value } = await reader.read();

                        if (done) {
                            console.log('SSE数据流已结束');
                            break;
                        }

                        // 解码接收到的数据块
                        const decodedChunk = decoder.decode(value, { stream: true });
                        buffer += decodedChunk;

                        // 记录所有接收到的数据，用于调试
                        allReceivedData += decodedChunk;

                        // 标记已收到数据
                        hasReceivedData = true;

                        // 处理接收到的数据行
                        let lastIndex = 0;
                        let linesProcessed = 0; // 记录处理的行数


                        while (true) {
                            const nextIndex = buffer.indexOf('\n', lastIndex);
                            if (nextIndex === -1) break;

                            // 获取一行数据并移除前后空白
                            const line = buffer.substring(lastIndex, nextIndex).trim();
                            lastIndex = nextIndex + 1;
                            linesProcessed++;


                            // 处理SSE格式的数据行
                            if (line.startsWith('data:')) {
                                // 提取data:后面的内容，兼容'data: '和'data:'两种格式
                                const data = line.startsWith('data: ') ? line.substring(6) : line.substring(5);

                                // 检查是否是完成标记
                                if (data === '[complete]') {
                                    if (!isCompleted) {
                                        isCompleted = true;
                                        const idx = this.messageListLocal.findIndex(x => x.id === messageId);
                                        if (idx > -1) {
                                            this.$set(this.messageListLocal, idx, {
                                                ...this.messageListLocal[idx],
                                                isStreaming: false
                                            });
                                        }
                                    }
                                    buffer = buffer.substring(lastIndex);
                                    return;
                                }

                                // 拼接消息内容，只有在未完成时才拼接
                                if (!isCompleted) {
                                    // 如果数据不是空行，则拼接到消息中
                                    if (data.trim() !== '') {
                                        // 检查是否有多个data:前缀的情况
                                        if (data.includes('data:')) {
                                            // 处理嵌套的data:前缀
                                            const nestedData = data.split('data:');
                                            for (const part of nestedData) {
                                                if (part.trim() !== '') {
                                                    // 替换换行符为<br>以确保正确显示
                                                    const formattedPart = part.trim().replace(/\n/g, '<br>');
                                                    fullMessage += formattedPart;
                                                    console.log('Added part to message:', formattedPart);
                                                }
                                            }
                                        } else {
                                            // 替换换行符为<br>以确保正确显示
                                            const formattedData = data.replace(/\n/g, '<br>');
                                            fullMessage += formattedData;
                                            console.log('Added data to message:', formattedData);
                                        }
                                    }

                                    // 更新UI显示
                                    const idx = this.messageListLocal.findIndex(x => x.id === messageId);
                                    if (idx > -1) {
                                        // 使用深拷贝确保响应式更新
                                        const updatedMessage = JSON.parse(JSON.stringify(this.messageListLocal[idx]));
                                        updatedMessage.text = fullMessage;
                                        this.$set(this.messageListLocal, idx, updatedMessage);
                                    }
                                }
                            }
                        }


                        // 处理剩余的buffer
                        buffer = buffer.substring(lastIndex);

                        // 如果buffer中还有内容但没有换行符，可能是不完整的行
                        if (buffer.length > 0) {

                            // 如果buffer以'data:'开头，且已经积累了一定长度，可以尝试处理它
                            // 这是为了处理最后一个数据块可能没有换行符的情况
                            if (buffer.startsWith('data:') && buffer.length > 10) {
                                const data = buffer.startsWith('data: ') ? buffer.substring(6) : buffer.substring(5);

                                if (!isCompleted && data.trim() !== '') {
                                    // 检查是否有多个data:前缀的情况
                                    if (data.includes('data:')) {
                                        // 处理嵌套的data:前缀
                                        const nestedData = data.split('data:');
                                        for (const part of nestedData) {
                                            if (part.trim() !== '') {
                                                const formattedPart = part.trim().replace(/\n/g, '<br>');
                                                fullMessage += formattedPart;
                                            }
                                        }
                                    } else {
                                        const formattedData = data.replace(/\n/g, '<br>');
                                        fullMessage += formattedData;
                                    }

                                    // 更新UI显示
                                    const idx = this.messageListLocal.findIndex(x => x.id === messageId);
                                    if (idx > -1) {
                                        const updatedMessage = JSON.parse(JSON.stringify(this.messageListLocal[idx]));
                                        updatedMessage.text = fullMessage;
                                        this.$set(this.messageListLocal, idx, updatedMessage);
                                    }
                                }

                                // 清空buffer，因为我们已经处理了它
                                buffer = '';
                            }
                        }

                        // 滚动到底部以显示最新消息
                        this.$nextTick(() => {
                            this.scrollToBottom();
                        });
                    }

                    // 清理资源
                    clearInterval(heartbeatInterval);
                    connectionActive = false;
                } catch (streamError) {
                    // 清理资源
                    clearInterval(heartbeatInterval);
                    connectionActive = false;

                    // 如果尚未完成且连接中断，尝试恢复连接
                    if (!isCompleted && retryCount < maxRetries) {
                        console.log('SSE连接中断，尝试恢复...');
                        retryCount++;
                        // 递归调用自身，尝试重新建立连接
                        return await this.streamEvaResponse(message, messageId);
                    }
                }
            } catch (error) {
                console.error('Fetch error:', error);
                // 处理错误情况
                const idx = this.messageListLocal.findIndex(x => x.id === messageId);
                if (idx > -1) {
                    this.$set(this.messageListLocal, idx, {
                        ...this.messageListLocal[idx],
                        text: fullMessage || '[回复生成失败]',
                        isStreaming: false
                    });
                }
                this.loading = false;
            }
        },
        scrollToBottom() {
            this.$nextTick(() => {
                const container = this.$refs.messageListContainer;
                if (container) {
                    // 确保滚动到最底部
                    container.scrollTop = container.scrollHeight;

                    // 添加一个延迟滚动，确保在DOM完全渲染后滚动
                    setTimeout(() => {
                        container.scrollTop = container.scrollHeight;
                    }, 200); // 增加延迟时间，确保DOM完全渲染
                }
            });
        },
        usePrompt(prompt) {
            this.InputMessage = prompt;
            this.send();
        },
        insertEmoji(emoji) {
            this.InputMessage += emoji;
            this.showEmojiPicker = false;
        },
        uploadImage() {
            this.$refs.imageInput.click();
        },
        async handleImageUpload(event) {
            const file = event.target.files[0];
            if (!file) return;

            if (file.size > 5 * 1024 * 1024) {
                this.$message.error('图片大小不能超过5MB');
                return;
            }

            const formData = new FormData();
            formData.append('file', file);

            try {
                const response = await postPic(formData);
                if (response.code === 200) {
                    const imageUrl = response.data;
                    this.InputMessage += `\n[图片](${imageUrl})\n`;
                    this.$message.success('图片上传成功');
                } else {
                    this.$message.error('图片上传失败');
                }
            } catch (error) {
                console.error('上传图片失败:', error);
                this.$message.error('图片上传失败');
            }

            // 清空input，以便可以重复上传同一文件
            event.target.value = '';
        }
    }
}
</script>

<style scoped>
.eva-container {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 20px;
    background: linear-gradient(135deg, #f5f7fa 0%, #e4e8f0 100%);
}

.eva-card {
    width: 95%;
    max-width: 1200px;
    height: 90vh;
    border-radius: 20px;
    background: #ffffff;
    box-shadow: 0 10px 30px rgba(0, 0, 0, 0.1);
    display: flex;
    flex-direction: column;
    overflow: hidden;
}

.eva-layout {
    display: grid;
    grid-template-columns: 280px 1fr;
    height: 100%;
}

.eva-sidebar {
    border-right: 1px solid #eaeaea;
    background: #f7f9fc;
    display: flex;
    flex-direction: column;
}

.sidebar-header {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 16px;
}

.sidebar-title {
    font-weight: 600;
    color: #334155;
}

.sidebar-actions {
    padding: 0 16px 12px 16px;
    display: grid;
    grid-template-columns: 1fr;
    gap: 8px;
}

.full-width {
    width: 100%;
}

.session-list {
    flex: 1;
    overflow-y: auto;
    padding: 8px 8px 16px 8px;
}

.session-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px;
    border-radius: 10px;
    background: #ffffff;
    border: 1px solid #eaeaea;
    margin-bottom: 8px;
    transition: all 0.2s;
}

.session-item:hover {
    box-shadow: 0 4px 12px rgba(0,0,0,0.06);
    transform: translateY(-1px);
}

.session-item.active {
    background: #e8f0fe;
    border-color: #c9d7ff;
}

.session-content {
    flex: 1;
    cursor: pointer;
    padding: 5px 0;
}

.session-name {
    font-size: 14px;
    color: #334155;
    font-weight: 500;
}

.session-actions {
    margin-left: 10px;
    opacity: 0;
    transition: opacity 0.3s;
}

.session-item:hover .session-actions {
    opacity: 1;
}

.session-empty {
    color: #94a3b8;
    text-align: center;
    padding: 20px 0;
}

.eva-main {
    display: flex;
    flex-direction: column;
}

.eva-header {
    padding: 20px;
    display: flex;
    align-items: center;
    background: linear-gradient(135deg, #456ddc 0%, #3a5dc0 100%);
    color: white;
}

.eva-avatar {
    margin-right: 15px;
}

.eva-info {
    flex: 1;
}

.eva-title {
    margin: 0;
    font-size: 22px;
    font-weight: 600;
}

.eva-status {
    display: flex;
    align-items: center;
    margin-top: 5px;
}

.status-dot {
    width: 8px;
    height: 8px;
    background-color: #4caf50;
    border-radius: 50%;
    margin-right: 5px;
    animation: pulse 2s infinite;
}

.status-text {
    font-size: 14px;
    opacity: 0.9;
}

.eva-actions {
    display: flex;
    gap: 10px;
}

.eva-divider {
    height: 1px;
    background-color: #eaeaea;
    margin: 0;
}

.eva-messages {
    flex: 1;
    overflow-y: auto;
    padding: 20px;
    background-color: #f9fafc;
    scroll-behavior: smooth;
    height: 0;
    min-height: 300px;
    display: flex;
    flex-direction: column;
}

.message-list {
    list-style: none;
    padding: 0;
    margin: 0;
    width: 100%;
    flex: 1;
}

.message-item {
    margin-bottom: 20px;
    display: flex;
    flex-direction: column;
}

.message-line {
    display: flex;
    align-items: flex-end;
}

.user-message .message-line {
    justify-content: flex-end;
}

.eva-message .message-line {
    justify-content: flex-start;
}

.avatar-container {
    margin: 0 8px;
}

.message-content {
    margin: 0 10px;
    padding: 10px 15px;
    border-radius: 18px;
    position: relative;
    word-break: break-word;
    max-width: 70%;
}

.user-message .message-content {
    background-color: #456ddc;
    color: white;
    border-top-left-radius: 4px;
}

.assistant-message .message-content {
    background-color: #f0f2f5;
    color: #333;
    border-top-right-radius: 4px;
}

.message-time {
    font-size: 12px;
    margin-top: 5px;
    opacity: 0.7;
    text-align: right;
}

.empty-chat {
    flex: 1;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: #999;
}

.empty-icon {
    font-size: 60px;
    margin-bottom: 20px;
    color: #456ddc;
    opacity: 0.5;
}

.quick-prompts-fixed {
    padding: 10px 20px;
    background-color: #f5f7fa;
    border-top: 1px solid #eaeaea;
    position: relative;
    z-index: 2;
}

.prompt-title {
    font-size: 14px;
    color: #666;
    margin-bottom: 8px;
}

.prompt-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
}

.prompt-tag {
    cursor: pointer;
    transition: all 0.3s;
}

.prompt-tag:hover {
    transform: translateY(-2px);
    box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.eva-input-area {
    padding: 20px;
    background-color: white;
    position: relative;
}

.input-container {
    display: flex;
    flex-direction: column;
}

.input-toolbar {
    display: flex;
    gap: 10px;
    margin-bottom: 5px;
}

.message-input {
    margin-bottom: 10px;
}

.message-input ::v-deep .el-textarea__inner {
    border-radius: 10px;
    border: 1px solid #e0e5ef;
    padding: 12px;
    resize: none;
    transition: all 0.3s;
}

.message-input ::v-deep .el-textarea__inner:focus {
    border-color: #456ddc;
    box-shadow: 0 0 0 2px rgba(69, 109, 220, 0.1);
}

.input-actions {
    display: flex;
    justify-content: flex-end;
}

.send-button {
    background-color: #456ddc;
    border-color: #456ddc;
    border-radius: 8px;
    padding: 10px 20px;
    font-weight: 500;
    display: flex;
    align-items: center;
    gap: 5px;
    transition: all 0.3s;
}

.send-button:hover {
    background-color: #3a5dc0;
    border-color: #3a5dc0;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(69, 109, 220, 0.3);
}

.send-button:active {
    transform: translateY(0);
}

.emoji-picker {
    position: absolute;
    bottom: 100%;
    left: 20px;
    background: white;
    border-radius: 8px;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
    padding: 10px;
    z-index: 10;
    width: 300px;
}

.emoji-list {
    display: grid;
    grid-template-columns: repeat(8, 1fr);
    gap: 5px;
}

.emoji-item {
    font-size: 20px;
    cursor: pointer;
    text-align: center;
    padding: 5px;
    border-radius: 4px;
    transition: all 0.2s;
}

.emoji-item:hover {
    background-color: #f0f2f5;
    transform: scale(1.2);
}

.typing-indicator {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 10px;
}

.typing-text {
    margin-left: 10px;
    color: #666;
    font-size: 14px;
}

.loader {
    padding: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
    --color: hsl(223, 54%, 56%);
    --animation: 2s ease-in-out infinite;
}

.loader .circle {
    display: flex;
    align-items: center;
    justify-content: center;
    position: relative;
    width: 20px;
    height: 20px;
    border: solid 2px var(--color);
    border-radius: 50%;
    margin: 0 10px;
    background-color: transparent;
    animation: circle-keys var(--animation);
}

.loader .circle .dot {
    position: absolute;
    transform: translate(-50%, -50%);
    width: 16px;
    height: 16px;
    border-radius: 50%;
    background-color: var(--color);
    animation: dot-keys var(--animation);
}

.loader .circle .outline {
    padding: 10px;
    position: absolute;
    transform: translate(-50%, -50%);
    width: 20px;
    height: 20px;
    border-radius: 50%;
    animation: outline-keys var(--animation);
}

@keyframes circle-keys {
    0% {
        transform: scale(1);
        opacity: 1;
    }

    50% {
        transform: scale(1.5);
        opacity: 0.5;
    }

    100% {
        transform: scale(1);
        opacity: 1;
    }
}

@keyframes dot-keys {
    0% {
        transform: scale(1);
    }

    50% {
        transform: scale(0.7);
    }

    100% {
        transform: scale(1);
    }
}

@keyframes outline-keys {
    0% {
        transform: scale(1);
        stroke-width: 3px;
        opacity: 1;
    }

    50% {
        transform: scale(1.5);
        stroke-width: 1px;
        opacity: 0.5;
    }

    100% {
        transform: scale(1);
        stroke-width: 3px;
        opacity: 1;
    }
}

@keyframes pulse {
    0% {
        box-shadow: 0 0 0 0 rgba(76, 175, 80, 0.7);
    }

    70% {
        box-shadow: 0 0 0 6px rgba(76, 175, 80, 0);
    }

    100% {
        box-shadow: 0 0 0 0 rgba(76, 175, 80, 0);
    }
}

.loading-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background-color: rgba(0, 0, 0, 0.5);
    display: flex;
    justify-content: center;
    align-items: center;
    z-index: 1000;
}

.help-dialog ::v-deep .el-dialog__header {
    background: linear-gradient(135deg, #456ddc 0%, #3a5dc0 100%);
    padding: 15px 20px;
}

.help-dialog ::v-deep .el-dialog__title {
    color: white;
    font-weight: 600;
}

.help-dialog ::v-deep .el-dialog__headerbtn .el-dialog__close {
    color: white;
}

.help-content {
    padding: 10px;
}

.help-content h3 {
    color: #456ddc;
    margin-bottom: 15px;
}

.help-content ul {
    padding-left: 20px;
    margin: 15px 0;
}

.help-content li {
    margin-bottom: 8px;
    color: #555;
}

.feature-grid {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
    margin-top: 20px;
}

.feature-item {
    display: flex;
    align-items: center;
    gap: 10px;
    padding: 15px;
    background-color: #f5f7fa;
    border-radius: 8px;
    transition: all 0.3s;
}

.feature-item:hover {
    transform: translateY(-3px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.feature-item i {
    font-size: 24px;
    color: #456ddc;
}

.feature-item span {
    font-weight: 500;
    color: #333;
}

/* 滚动条样式 */
.eva-messages::-webkit-scrollbar {
    width: 6px;
}

.eva-messages::-webkit-scrollbar-track {
    background: rgba(224, 224, 224, 0.13);
}

.eva-messages::-webkit-scrollbar-thumb {
    background: #989898;
    border-radius: 3px;
}

.eva-messages::-webkit-scrollbar-thumb:hover {
    background: #555;
}
</style>
